package mutil

import (
	"bytes"
	"gitee.com/dennis-mxx/mxx-core-v2/mlogger"
	"github.com/goccy/go-json"
	"io"
	"net/http"
	"strings"
	"time"
)

var client = http.Client{Timeout: 3 * time.Second}

type DingTextMessage struct {
	ServerName string
	Method     string
	Url        string
	Message    string
}

func SendWebHookDingDing(url string, message DingTextMessage) {
	build := strings.Builder{}
	build.WriteString("来源系统: ")
	build.WriteString(message.ServerName)
	build.WriteString("\n")
	build.WriteString("通知时间: ")
	build.WriteString(DateUtil.NowDateTimeStr())
	build.WriteString("\n")
	build.WriteString("请求地址: ")
	build.WriteString(message.Url)
	build.WriteString("\n")
	build.WriteString("请求方法: ")
	build.WriteString(message.Method)
	build.WriteString("\n")
	build.WriteString("错误信息: \n")
	build.WriteString(message.Message)

	data := map[string]any{
		"msgtype": "text",
		"text": map[string]string{
			"content": build.String(),
		},
	}
	b, _ := json.Marshal(data)

	resp, err := client.Post(url, "application/json;charset=UTF-8", bytes.NewReader(b))
	if err != nil {
		mlogger.Out.Error("发送钉钉错误日志失败 :", err)
	} else {
		b, err = io.ReadAll(resp.Body)
		if err != nil {
			mlogger.Out.Error("读取钉钉错误日志返回值失败 :", err)
		} else {
			mlogger.Out.Info("发送钉钉错误日志成功 ! --- > resp : ", string(b))
		}
	}

}
